#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/un.h>

#define path_socket_unix "/home/utn_so/miSocketUnix"
#define SOCKET_MAX_BUFFER 512

void * cambiarTamano (void *, unsigned int, unsigned int);
void recibirDatos(int);


void recibirDatos(int client)
{
	char cadena;
	char * vectorDinamico = NULL;
	int tamano = 0;
	int cantBytesLeidos = 0;

	while(1){

		cantBytesLeidos = recv(client, &cadena, 1, 0);
		vectorDinamico = (char *) cambiarTamano(vectorDinamico, sizeof(char), tamano + cantBytesLeidos);
		memcpy(vectorDinamico + tamano, &cadena, cantBytesLeidos);
		tamano += cantBytesLeidos;
		
	}
	printf("La cadena enviada es : %s\n", vectorDinamico);
}

void * cambiarTamano (void * vector, unsigned int tamElem, unsigned int cantidad) {
  if (!(cantidad && tamElem)) {
    if (vector) free(vector);
    return NULL;
  } else if (!vector)
    return malloc(tamElem * cantidad);
  else
    return realloc(vector, tamElem * cantidad);
}



int main(int argc, char **argv) {

	//conectar

	int addrlen = sizeof(struct sockaddr_un);
	/*char buffer[SOCKET_MAX_BUFFER];
	char buffer2[SOCKET_MAX_BUFFER];*/

	int descriptor = socket(AF_UNIX, SOCK_STREAM, 0);
	int client;

	struct  sockaddr_un * datosSocket = malloc(sizeof(struct sockaddr_un));


	datosSocket->sun_family = AF_UNIX;
	strcpy(datosSocket->sun_path, path_socket_unix);
	unlink(path_socket_unix);

	bind(descriptor,(struct sockaddr *) datosSocket, sizeof(struct sockaddr_un));

	listen(descriptor, 1);

	client = accept(descriptor,(struct sockaddr *) datosSocket, (void *)&addrlen);


	//recivir
	recibirDatos(client);

	/*recv(client,buffer2,SOCKET_MAX_BUFFER,0);

	printf("La segunda cadena enviada es : %s\n", buffer2);*/

	close(descriptor);




	return EXIT_SUCCESS;


}